package server;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * servlet 封装类
 */
public class Wrapper {
    private Servlet servletInstance;

    private Wrapper() {

    }

    /**
     * 根据 servlet 名和类构建 servlet 实例
     *
     * @param servletName
     * @param servletClass
     * @return
     * @throws Exception
     */
    public static Wrapper build(Context context, String servletName, String servletClass) throws Exception {
        Wrapper wrapper = new Wrapper();
        File classDir = context.getContextDir();
        URL url = classDir.toURI().toURL();
        URL[] urls = new URL[]{url};
        ClassLoader cl = new URLClassLoader(urls);
        Object cls = cl.loadClass(servletClass).getDeclaredConstructor().newInstance();
        if (!(cls instanceof Servlet)) {
            throw new Exception(String.format("类[%s]不是有效的Servlet实例", servletClass));
        }
        wrapper.servletInstance = (Servlet) cls;
        return wrapper;
    }

    public Servlet getServletInstance() {
        return servletInstance;
    }

}
